package servlet;

import Dao.JdbcTools;
import Dao.UserMapper;
import model.Student;
import model.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/islogin")
public class UserRequest2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String user = req.getParameter("user");
        String pw = req.getParameter("pw");
        String code = req.getParameter("yz");
        System.out.println("user = " + user);
        System.out.println("pw = " + pw);
        System.out.println("code = " + code);
        //1判断用户输入的验证码和机器验证码是否相同
        HttpSession session = req.getSession();
        String yz = (String) session.getAttribute("yz");
        if (!yz.equals(code))
        {
            System.out.println("验证码错误！");
            return;
        }

        //访问Dao，查询记录

        //调用数据访问层
        InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
//从配置文件中获取一个工厂对象
        SqlSessionFactory fac = new SqlSessionFactoryBuilder().build(in);
//通过工厂获取sqlsession对象
        SqlSession sqlSession = fac.openSession();
//sqlsession对象执行映射mapper文件中的sql语句
        User user2 = new User(user,pw);
        UserMapper mapper=sqlSession.getMapper(UserMapper.class);
        User user1 = mapper.dengUser(user2);

        if(user1==null)
            {
                //错误提示servlet
                req.getRequestDispatcher("usererror").forward(req,resp);
            }else{
                //获取数据库中展示数据
            List<Student> stulist= mapper.getUserById();
            //数据展示 servlet
                req.setAttribute("stulist",stulist);
                req.getRequestDispatcher("showlist").forward(req,resp);


        }
    }
}
